<template>
  <div>
    <div>
      <div class="title mb-10px">基本信息</div>
      <el-form ref="formRef" label-width="110px" :inline="true" v-loading="formLoading">
        <el-form-item v-for="(item, index) in baseJson" :key="index" :label="item.label" prop="checkTaskNumber">
          <el-select v-if="item.needFormatter" v-model="formData[item.field]" placeholder="" class="!w-220px" disabled>
            <el-option v-for="dict, index in getIntDictOptions('dict_delivery_type')" :key="index" :label="dict.label"
              :value="dict.value" />
          </el-select>
          <el-input v-else disabled v-model="formData[item.field]" class="!w-220px" />
        </el-form-item>
      </el-form>
    </div>
    <div>
      <div class="title mb-10px">运输信息</div>
      <!-- 20 物流 -->
      <el-form 
        ref="shippingRef" 
        label-width="110px" 
        :inline="true" 
        :model="formData"
        :rules="shippingRules"
        v-loading="formLoading"
        v-if="formData.dictDeliveryType === 20"
      >
        <el-form-item label="物流单号" prop="shippingNumber">
          <el-input 
            :disabled="formType === 'view' || ['logistics'].includes(moduleName)"
            v-model="formData.shippingNumber" class="!w-220px" 
          />
        </el-form-item>
      </el-form>
      <!-- 30 快递 -->
      <el-form 
        ref="courierRef" 
        label-width="110px" 
        :inline="true" 
        v-loading="formLoading"
        :model="formData"
        :rules="courierRules"
        v-else-if="formData.dictDeliveryType === 30"
      >
        <el-form-item label="快递单号" prop="courierNumber">
          <el-input 
            :disabled="formType === 'view' || ['logistics'].includes(moduleName)" 
            v-model="formData.courierNumber"
            class="!w-220px" 
          />
        </el-form-item>
      </el-form>
      <!-- 40 集装箱 -->
      <el-form ref="boxRef" 
        label-width="110px" 
        :inline="true" 
        :model="formData"
        :rules="boxRules"
        v-loading="formLoading"
        v-else-if="formData.dictDeliveryType === 40"
      >
        <el-form-item label="集装箱号" prop="containerNumber">
          <el-input 
            :disabled="formType === 'view' || ['logistics'].includes(moduleName)"
            v-model="formData.containerNumber" class="!w-220px" 
          />
        </el-form-item>
        <el-form-item label="箱型尺寸" prop="containerSize">
          <el-input 
            :disabled="formType === 'view' || ['logistics'].includes(moduleName)" 
            v-model="formData.containerSize"
            class="!w-220px" 
          />
        </el-form-item>
        <el-form-item label="锁号" prop="lockNumber">
          <el-input 
            :disabled="formType === 'view' || ['logistics'].includes(moduleName)" 
            v-model="formData.lockNumber"
            class="!w-220px" 
          />
        </el-form-item>
      </el-form>
      <!-- 60 其他 -->
      <el-form 
        ref="otherRef" 
        label-width="110px" 
        :inline="true" 
        :model="formData"
        :rules="otherRules"
        v-loading="formLoading"
        v-else-if="formData.dictDeliveryType === 60"
      >
        <el-form-item label="发货方式" prop="sendMethod">
          <el-input 
            :disabled="formType === 'view' || ['logistics'].includes(moduleName)" 
            v-model="formData.sendMethod"
            class="!w-220px" 
          />
        </el-form-item>
        <el-form-item label=" 联系人" prop="contactName">
          <el-input 
            :disabled="formType === 'view' || ['logistics'].includes(moduleName)" 
            v-model="formData.contactName"
            class="!w-220px" 
          />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactPhone">
          <el-input 
            :disabled="formType === 'view' || ['logistics'].includes(moduleName)" 
            v-model="formData.contactPhone"
            class="!w-220px" 
          />
        </el-form-item>
      </el-form>
      <!-- 10 请车 -->
      <el-form 
        label-width="110px" 
        :inline="true" 
        v-loading="formLoading" 
        v-else
      >
        <el-form-item label="车牌" prop="licencePlate">
          <el-input disabled v-model="formData.licencePlate" class="!w-220px" />
        </el-form-item>
        <el-form-item label="司机称呼" prop="driverName">
          <el-input disabled v-model="formData.driverName" class="!w-220px" />
        </el-form-item>
        <el-form-item label="司机电话" prop="driverPhone">
          <el-input disabled v-model="formData.driverPhone" class="!w-220px" />
        </el-form-item>
      </el-form>
      <!-- 60 其他、 -->
      <el-form label-width="110px" v-if="[20, 30, 60].includes(formData.dictDeliveryType)">
        <el-form-item label="附件上传">
          <template v-if="formType === 'update' && !['logistics'].includes(moduleName)">
            <UploadFile 
              style="width: auto" 
              v-if="formData.fileList" 
              v-model="formData.fileList" 
              :isShowTip="false"
              :limit="20" 
              :fileSize="200" 
              :fileType="['pdf', 'png', 'jpg']" 
              @update:modelValue="uploadFile" 
            />
          </template>
          <template v-else-if="(formType === 'view' || ['logistics'].includes(moduleName)) && formData.files">
            <el-button 
              link type="primary" 
              v-for="item, index in formData.files" 
              :key="index"
              @click="openFile(item['filePath'])"
            >
              {{ item['fileName'] }}
            </el-button>
          </template>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <div class="title mb-10px">发货明细</div>
      <div class="btn mb-10px">
        <el-button type="primary" v-if="formType === 'update' && !['logistics'].includes(moduleName)"
          @click="openChoosePart">选择部件</el-button>
      </div>
      <el-table border v-loading="formLoading" ref="multipleTableRef" :data="formData.details">
        <el-table-column type="index" label="序号" align="center" />
        <el-table-column v-for="item, index in otherTableTitle" :key="index" :label="item.label"
          :header-align="item.headerAlign" :align="item.align" :prop="item.field" min-width="200px">
          <template #default="scope">
            <!-- 发货数量 -->
            <el-input-number v-nextInput="'sendQuantity'"  name="sendQuantity" v-if="item.field === 'sendQuantity'" 
              v-model="scope.row.sendQuantity"
              :disabled="formType === 'view' || ['logistics'].includes(moduleName)" />
            <!-- 集装箱跳转 -->
            <el-button
              v-else-if="item.field === 'partName' && scope.row.isBox === 1"
              link
              type="primary"
              @click="goBox(scope.row.sourceId)"
            >
              {{ scope.row['partName'] }}
            </el-button>
            <!-- 字典翻译 -->
            <dict-tag v-else-if="['dictIncomingType'].includes(item.field)" type="incoming_type"
              :value="scope.row[item.field]" />
            <div v-else>{{ scope.row[item.field] }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="left" align="left"
          v-if="formType === 'update' && !['logistics'].includes(moduleName)">
          <template #default="scope">
            <el-button link type="danger" @click="handleDelete(scope.$index)">
              删除行
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <choosePart ref="choosePartRef" @setParts="setParts" />
  </div>
</template>
<script setup lang="ts">
import { getIntDictOptions } from '@/utils/dict'
import choosePart from './choosePart.vue'
// import * as ProductionShipmentsApi from '@/api/produce/productManagement/productionShipments'

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  sendNumber: undefined,
  inventoryId: undefined,
  dictDeliveryType: undefined,
  customerName: undefined,
  productStandard: undefined,
  productSize: undefined,
  trainNumber: undefined,
  customerAddress: undefined,
  packingAddress: undefined,
  requirements: undefined,
  loadingStartTime: undefined,
  loadingEndTime: undefined,
  licencePlate: undefined,
  driverName: undefined,
  driverPhone: undefined,
  containerNumber: undefined,
  containerSize: undefined,
  lockNumber: undefined,
  shippingNumber: undefined,
  courierNumber: undefined,
  sendMethod: undefined,
  contactName: undefined,
  contactPhone: undefined,
  sendName: undefined,
  receiveName: undefined,
  creatorName: undefined,
  updaterName: undefined,
  dictDeliveryStatus: undefined,
  trackingNumber: undefined,
  files: null, //运输信息附件
  receiveFiles: [], //签收附件
  receiveFilePath: undefined,
  receiveFileName: undefined,
  details: [], //部件列表
  fileList: [],
  prepareId: undefined,  //清单id
  deliveryDate: undefined //发货时间
})

// moduleName： logistics 物流模块 shipments 发货管理模块

const props = defineProps({
  detailData: {
    type: Object,
    default: () => { }
  },
  formType: String,
  moduleName: {
    type: String,
    default: ''
  }
})

const choosePartRef = ref()

const courierRef = ref()
const shippingRef = ref()
const boxRef = ref()
const otherRef = ref()
// 快递校验规则
const courierRules = reactive({
  courierNumber: [{ required: true, message: '快递单号不能为空', trigger: 'blur' }]
})
// 物流校验规则
const shippingRules = reactive({
  shippingNumber: [{ required: true, message: '物流单号不能为空', trigger: 'blur' }]
})
// 集装箱校验规则
const boxRules = reactive({
  containerNumber: [{ required: true, message: '集装箱号不能为空', trigger: 'blur' }],
  containerSize: [{ required: true, message: '箱型尺寸不能为空', trigger: 'blur' }],
  lockNumber: [{ required: true, message: '锁号不能为空', trigger: 'blur' }]
})
// 其他校验规则
const otherRules = reactive({
  sendMethod: [{ required: true, message: '发货方式不能为空', trigger: 'blur' }],
  contactName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }]
})

// 基本信息
const baseJson = [
  {
    label: '发货单号',
    field: 'trackingNumber',
    needFormatter: false
  },
  {
    label: '发货申请单号',
    field: 'sendNumber',
    needFormatter: false
  },
  {
    label: '发货类型',
    field: 'dictDeliveryType',
    needFormatter: true,
    dict: 'dict_delivery_type'
  },
  {
    label: '客户名称',
    field: 'customerName',
    needFormatter: false
  },
  {
    label: '产品尺寸',
    field: 'productSize',
    needFormatter: false
  },
  {
    label: '客户地址',
    field: 'customerAddress',
    needFormatter: false
  },
  {
    label: '装货地点',
    field: 'packingAddress',
    needFormatter: false
  },
  {
    label: '特殊要求',
    field: 'requirements',
    needFormatter: false
  }
]

// 发货类型表头
const otherTableTitle = [
  {
    label: '清单编号',
    field: 'prepareNumber',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '产品编号',
    field: 'productNumber',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '部件编码',
    field: 'partNumber',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '部件名称',
    field: 'partName',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '部件规格',
    field: 'partSpecification',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '图纸图号',
    field: 'partDrawingNumber',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '备货剩余数量',
    field: 'prepareRemaQuantity',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '发货数量',
    field: 'sendQuantity',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '单位',
    field: 'partUnit',
    headerAlign: 'left',
    align: 'left'
  },
  // {
  //   label: '入库类型',
  //   field: 'dictIncomingType',
  //   headerAlign: 'left',
  //   align: 'left'
  // },
  {
    label: '仓库名称',
    field: 'warehouseName',
    headerAlign: 'left',
    align: 'left'
  }
]

// 箱子跳转
const { push } = useRouter() // 路由
const goBox = (id: number) => {
  console.log(id)
  push({
    path:'/produce/produce/productManagement/productionPreparePackingForm',
    query: {
      type: 'view',
      id
    }
  })
}

// 查看附件
const openFile = (path: string) => {
  window.open(path)
}

// 运输信息附件上传
const uploadFile = (data) => {
  if (JSON.parse(data).length) {
    formData.value.files = JSON.parse(data).map(item => {
      return {
        fileName: item.name,
        filePath: item.url
      }
    })
  } else {
    formData.value.files = null
  }
}

// 删除行
const handleDelete = (index: number) => {
  formData.value.details.splice(index, 1)
}

// 打开选择部件弹窗
const openChoosePart = () => {
  choosePartRef.value.open(formData.value.details, formData.value.prepareId)
}

// 选择部件
const setParts = (val) => {
  val.map(item => {
    item.sourceId = item.id
    item.sendQuantity = null
    delete item.id
    return item
  })
  formData.value.details = val
}

defineExpose({ formData })

watch(
  () => props.detailData,
  () => {
    formData.value = props.detailData
    // 设置附件回显
    if (props.detailData.files) {
      formData.value.fileList = props.detailData.files.map(item => {
        return {
          name: item['fileName'],
          url: item['filePath']
        }
      })
    } else {
      formData.value.fileList = []
    }
  }
)
</script>
<style lang="scss" scoped>
.title {
  font-weight: bold;
}

.btn {
  display: flex;
  justify-content: flex-end;
}</style>
